/*
 * @Description  : 车牌键盘
 * @Date         : 2021-08-18 15:38:09
 * @Author       : 保锋
 * @LastEditTime : 2021-08-26 14:57:54
 * @LastEditors  : 保锋
 * @FilePath     : \flutter_demo\lib\pages\car_number_input\car_number_input_index.dart
 */
import 'dart:ui';

import 'package:flutter/material.dart';
import './config.dart';
import 'package:flutter_vibrate/flutter_vibrate.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'action.dart';
import 'dialog_strategy.dart';

class CarNumberInputPage extends StatefulWidget {
  CarNumberInputPage({Key? key}) : super(key: key);

  @override
  _CarNumberInputPageState createState() => _CarNumberInputPageState();
}

class _CarNumberInputPageState extends State<CarNumberInputPage> {
  ///首字母键盘
  List<CarNumberInputButtonItem> firstCarNameList = <CarNumberInputButtonItem>[
    CarNumberInputButtonItem(title: '京'),
    CarNumberInputButtonItem(title: '津'),
    CarNumberInputButtonItem(title: '渝'),
    CarNumberInputButtonItem(title: '沪'),
    CarNumberInputButtonItem(title: '冀'),
    CarNumberInputButtonItem(title: '晋'),
    CarNumberInputButtonItem(title: '辽'),
    CarNumberInputButtonItem(title: '吉'),
    CarNumberInputButtonItem(title: '黑'),
    CarNumberInputButtonItem(title: '苏'),
    CarNumberInputButtonItem(title: '浙'),
    CarNumberInputButtonItem(title: '皖'),
    CarNumberInputButtonItem(title: '闽'),
    CarNumberInputButtonItem(title: '赣'),
    CarNumberInputButtonItem(title: '鲁'),
    CarNumberInputButtonItem(title: '豫'),
    CarNumberInputButtonItem(title: '鄂'),
    CarNumberInputButtonItem(title: '湘'),
    CarNumberInputButtonItem(title: '粤'),
    CarNumberInputButtonItem(title: '琼'),
    CarNumberInputButtonItem(title: '川'),
    CarNumberInputButtonItem(title: '贵'),
    CarNumberInputButtonItem(title: '云'),
    CarNumberInputButtonItem(title: '陕'),
    CarNumberInputButtonItem(title: '甘'),
    CarNumberInputButtonItem(title: '青'),
    CarNumberInputButtonItem(title: '蒙'),
    CarNumberInputButtonItem(title: '桂'),
    CarNumberInputButtonItem(title: '宁', type: CarType.primary),
    CarNumberInputButtonItem(
      title: '新',
    ),
    CarNumberInputButtonItem(
      title: '藏',
    ),
    CarNumberInputButtonItem(title: '军', type: CarType.hide),
    CarNumberInputButtonItem(title: '警', type: CarType.hide),
    CarNumberInputButtonItem(title: '学', type: CarType.hide),
    CarNumberInputButtonItem(title: '港', type: CarType.hide),
    CarNumberInputButtonItem(title: '澳', type: CarType.hide),
    CarNumberInputButtonItem(title: '删除', type: CarType.delete),
    CarNumberInputButtonItem(title: '完成', type: CarType.success),
  ];

  ///第二个字母键盘
  List<CarNumberInputButtonItem> secondCarNameList = <CarNumberInputButtonItem>[
    CarNumberInputButtonItem(title: '1', type: CarType.disable),
    CarNumberInputButtonItem(title: '2', type: CarType.disable),
    CarNumberInputButtonItem(title: '3', type: CarType.disable),
    CarNumberInputButtonItem(title: '4', type: CarType.disable),
    CarNumberInputButtonItem(title: '5', type: CarType.disable),
    CarNumberInputButtonItem(title: '6', type: CarType.disable),
    CarNumberInputButtonItem(title: '7', type: CarType.disable),
    CarNumberInputButtonItem(title: '8', type: CarType.disable),
    CarNumberInputButtonItem(title: '9', type: CarType.disable),
    CarNumberInputButtonItem(title: '0', type: CarType.disable),
    CarNumberInputButtonItem(title: 'Q'),
    CarNumberInputButtonItem(title: 'W'),
    CarNumberInputButtonItem(title: 'E'),
    CarNumberInputButtonItem(title: 'R'),
    CarNumberInputButtonItem(title: 'T'),
    CarNumberInputButtonItem(title: 'Y'),
    CarNumberInputButtonItem(title: 'U'),
    CarNumberInputButtonItem(title: 'I', type: CarType.disable),
    CarNumberInputButtonItem(title: 'O', type: CarType.disable),
    CarNumberInputButtonItem(title: 'P'),
    CarNumberInputButtonItem(title: 'A'),
    CarNumberInputButtonItem(title: 'S'),
    CarNumberInputButtonItem(title: 'D'),
    CarNumberInputButtonItem(title: 'F'),
    CarNumberInputButtonItem(title: 'G'),
    CarNumberInputButtonItem(title: 'H'),
    CarNumberInputButtonItem(title: 'J'),
    CarNumberInputButtonItem(title: 'K'),
    CarNumberInputButtonItem(
      title: 'L',
    ),
    CarNumberInputButtonItem(
      title: 'Z',
    ),
    CarNumberInputButtonItem(
      title: 'X',
    ),
    CarNumberInputButtonItem(title: 'M'),
    CarNumberInputButtonItem(title: 'C'),
    CarNumberInputButtonItem(title: 'V'),
    CarNumberInputButtonItem(title: 'B'),
    CarNumberInputButtonItem(title: 'N'),
    CarNumberInputButtonItem(title: '删除', type: CarType.delete),
    CarNumberInputButtonItem(title: '完成', type: CarType.success),
  ];
  List<CarNumberInputButtonItem> otherCarNameList = <CarNumberInputButtonItem>[
    CarNumberInputButtonItem(title: '1'),
    CarNumberInputButtonItem(title: '2'),
    CarNumberInputButtonItem(title: '3'),
    CarNumberInputButtonItem(title: '4'),
    CarNumberInputButtonItem(title: '5'),
    CarNumberInputButtonItem(title: '6'),
    CarNumberInputButtonItem(title: '7'),
    CarNumberInputButtonItem(title: '8'),
    CarNumberInputButtonItem(title: '9'),
    CarNumberInputButtonItem(title: '0'),
    CarNumberInputButtonItem(title: 'Q'),
    CarNumberInputButtonItem(title: 'W'),
    CarNumberInputButtonItem(title: 'E'),
    CarNumberInputButtonItem(title: 'R'),
    CarNumberInputButtonItem(title: 'T'),
    CarNumberInputButtonItem(title: 'Y'),
    CarNumberInputButtonItem(title: 'U'),
    CarNumberInputButtonItem(title: 'I', type: CarType.disable),
    CarNumberInputButtonItem(title: 'O', type: CarType.disable),
    CarNumberInputButtonItem(title: 'P'),
    CarNumberInputButtonItem(title: 'A'),
    CarNumberInputButtonItem(title: 'S'),
    CarNumberInputButtonItem(title: 'D'),
    CarNumberInputButtonItem(title: 'F'),
    CarNumberInputButtonItem(title: 'G'),
    CarNumberInputButtonItem(title: 'H'),
    CarNumberInputButtonItem(title: 'J'),
    CarNumberInputButtonItem(title: 'K'),
    CarNumberInputButtonItem(
      title: 'L',
    ),
    CarNumberInputButtonItem(
      title: 'Z',
    ),
    CarNumberInputButtonItem(
      title: 'X',
    ),
    CarNumberInputButtonItem(title: 'M'),
    CarNumberInputButtonItem(title: 'C'),
    CarNumberInputButtonItem(title: 'V'),
    CarNumberInputButtonItem(title: 'B'),
    CarNumberInputButtonItem(title: 'N'),
    CarNumberInputButtonItem(title: '删除', type: CarType.delete),
    CarNumberInputButtonItem(title: '完成', type: CarType.success),
  ];
  List<CarNumberInputButtonItem> specialCarNameList =
      <CarNumberInputButtonItem>[
    CarNumberInputButtonItem(title: '1'),
    CarNumberInputButtonItem(title: '2'),
    CarNumberInputButtonItem(title: '3'),
    CarNumberInputButtonItem(title: '4'),
    CarNumberInputButtonItem(title: '5'),
    CarNumberInputButtonItem(title: '6'),
    CarNumberInputButtonItem(title: '7'),
    CarNumberInputButtonItem(title: '8'),
    CarNumberInputButtonItem(title: '9'),
    CarNumberInputButtonItem(title: '0'),
    CarNumberInputButtonItem(title: 'Q'),
    CarNumberInputButtonItem(title: 'W'),
    CarNumberInputButtonItem(title: 'E'),
    CarNumberInputButtonItem(title: 'R'),
    CarNumberInputButtonItem(title: 'T'),
    CarNumberInputButtonItem(title: 'Y'),
    CarNumberInputButtonItem(title: 'U'),
    // CarNumberInputButtonItem(title: 'I', type: CarType.disable),
    // CarNumberInputButtonItem(title: 'O', type: CarType.disable),
    CarNumberInputButtonItem(title: 'P'),
    CarNumberInputButtonItem(title: 'A'),
    CarNumberInputButtonItem(title: 'S'),
    CarNumberInputButtonItem(title: 'D'),
    CarNumberInputButtonItem(title: 'F'),
    CarNumberInputButtonItem(title: 'G'),
    CarNumberInputButtonItem(title: 'H'),
    CarNumberInputButtonItem(title: 'J'),
    CarNumberInputButtonItem(title: 'K'),
    CarNumberInputButtonItem(
      title: 'L',
    ),
    CarNumberInputButtonItem(
      title: 'Z',
    ),
    CarNumberInputButtonItem(
      title: 'X',
    ),
    CarNumberInputButtonItem(title: 'M'),
    CarNumberInputButtonItem(title: 'C'),
    CarNumberInputButtonItem(title: 'V'),
    CarNumberInputButtonItem(title: 'B'),
    CarNumberInputButtonItem(title: 'N'),
    CarNumberInputButtonItem(title: '学', type: CarType.special),
    CarNumberInputButtonItem(title: '警', type: CarType.special),
    CarNumberInputButtonItem(title: '挂', type: CarType.special),
    CarNumberInputButtonItem(title: '删除', type: CarType.delete),
    CarNumberInputButtonItem(title: '完成', type: CarType.success),
  ];

  List<RxString> carNumberList = <RxString>[
    '宁'.obs,
    ''.obs,
    ''.obs,
    ''.obs,
    ''.obs,
    ''.obs,
    ''.obs,
    ''.obs
  ];

  RxInt listIndex = (-1).obs;

  RxBool isOpenKeyboard = false.obs;

  ///SmartDialog相关配置,使用Config管理
  late Config config;

  late OverlayEntry entryMain;

  late DialogAction _mainAction;

  RxString initialValue = ''.obs;

  @override
  void initState() {
    config = Config();

    entryMain = OverlayEntry(
      builder: (BuildContext context) {
        return _mainAction.getWidget();
      },
    );
    _mainAction = DialogStrategy(config: config, overlayEntry: entryMain);

    ///将新的遮罩层插入视图堆栈

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('车牌号输入'),
      ),
      body: Column(
        children: [
          Container(
            width: 200.w,
            // color: Colors.red,
            child: GestureDetector(
              onTap: () {
                print('弹出键盘');
                if (isOpenKeyboard.value) {
                  entryMain.remove();
                  isOpenKeyboard.value = false;

                  listIndex.value = -1;
                } else {
                  listIndex.value = 1;
                  isOpenKeyboard.value = true;
                  Overlay.of(context)!.insert(entryMain);
                  show(
                    widget: Obx(() {
                      switch (listIndex.value) {
                        case 0:
                          return carNumberInputKeyboard(data: firstCarNameList);
                        case 1:
                          return carNumberInputKeyboard(
                              data: secondCarNameList);
                        case 6:
                          return carNumberInputKeyboard(
                              data: specialCarNameList);
                        default:
                          return carNumberInputKeyboard(data: otherCarNameList);
                      }
                    }),
                    alignmentTemp: Alignment.bottomCenter,
                    isPenetrateTemp: true,
                    clickBgDismissTemp: false,
                  );
                }
              },
              child: WillPopScope(
                onWillPop: () async {
                  if (isOpenKeyboard.value) {
                    entryMain.remove();
                    isOpenKeyboard.value = false;
                    return false;
                  } else {
                    return true;
                  }
                },
                child: Obx(() => Text(
                      initialValue.value == '' ? '请输入车牌号' : initialValue.value,
                      style: TextStyle(color: Colors.black),
                    )),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> show({
    required Widget widget,
    AlignmentGeometry? alignmentTemp,
    bool? isPenetrateTemp,
    bool? isUseAnimationTemp,
    Duration? animationDurationTemp,
    bool? isLoadingTemp,
    Color? maskColorTemp,
    bool? clickBgDismissTemp,
    //overlay弹窗消失回调
    VoidCallback? onDismiss,
  }) {
    return _mainAction.show(
      widget: widget,
      alignment: alignmentTemp ?? config.alignment,
      isPenetrate: isPenetrateTemp ?? config.isPenetrate,
      isUseAnimation: isUseAnimationTemp ?? config.isUseAnimation,
      animationDuration: animationDurationTemp ?? config.animationDuration,
      isLoading: isLoadingTemp ?? config.isLoading,
      maskColor: maskColorTemp ?? config.maskColor,
      clickBgDismiss: clickBgDismissTemp ?? config.clickBgDismiss,
      onDismiss: onDismiss,
    );
  }

  ///车牌数字项目
  Widget renderCarNumberItem(RxString text, int index) {
    final Color color = () {
      if (index == 0) {
        return Colors.red;
      } else if (index == 7) {
        return Colors.green;
      } else {
        return Colors.black;
      }
    }();
    return GestureDetector(
      onTap: () {
        listIndex.value = index;
      },
      child: Container(
        height: 120.w,
        decoration: BoxDecoration(
            border: Border.all(
                color: listIndex.value == index
                    ? Color.fromRGBO(243, 72, 62, 1)
                    : Color.fromRGBO(208, 213, 217, 1),
                width: 2.w)),
        child: Center(
          child: Text(
            index == 7 && text.value == '' ? '新' : text.value,
            style: TextStyle(
              color: color,
              fontSize: 60.sp,
              fontWeight: FontWeight.w600,
              decoration: TextDecoration.none,
            ),
          ),
        ),
      ),
    );
  }

  ///车牌键盘
  Widget carNumberInputKeyboard(
      {required List<CarNumberInputButtonItem> data}) {
    return SafeArea(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: 1.sw,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: carNumberList.asMap().keys.map((int index) {
                return Expanded(
                    child: renderCarNumberItem(carNumberList[index], index));
              }).toList(),
            ),
          ),
          Container(
            width: 1.sw,
            color: const Color.fromRGBO(208, 213, 217, 1),
            child: Padding(
              padding: EdgeInsets.only(
                  top: 30.w, left: 10.w, right: 10.w, bottom: 30.w),
              child: Wrap(
                  alignment: WrapAlignment.center,
                  spacing: 15.w,
                  runSpacing: 15.w,
                  children: data.map((CarNumberInputButtonItem e) {
                    return carNumberButton(title: e.title, type: e.type);
                  }).toList()),
            ),
          ),
        ],
      ),
    );
  }

  ///键盘按钮
  Widget carNumberButton(
      {required String title, CarType type = CarType.normal}) {
    ///背景颜色
    late MaterialStateProperty<Color?>? backgroundColor;

    ///波纹颜色
    late MaterialStateProperty<Color?>? overlayColor;

    ///字体颜色
    late Color? fontColor;

    ///默认样式
    backgroundColor = MaterialStateProperty.all(Colors.white);
    overlayColor = MaterialStateProperty.resolveWith(
      (Set<MaterialState> states) {
        const Set<MaterialState> interactiveStates = <MaterialState>{
          MaterialState.pressed,
          MaterialState.hovered,
          MaterialState.focused,
        };
        if (states.any(interactiveStates.contains)) {
          return Colors.grey[300];
        } else {
          return Colors.white;
        }
      },
    );
    fontColor = Colors.black;
    const Set<MaterialState> interactiveStates = <MaterialState>{
      MaterialState.pressed,
      MaterialState.hovered,
      MaterialState.focused,
    };
    switch (type) {
      case CarType.primary:
        fontColor = Colors.red;
        break;
      case CarType.delete:
        backgroundColor = MaterialStateProperty.all(Colors.blue);
        overlayColor = MaterialStateProperty.resolveWith(
          (Set<MaterialState> states) {
            if (states.any(interactiveStates.contains)) {
              return Colors.blue[300];
            } else {
              return Colors.white;
            }
          },
        );
        fontColor = Colors.white;
        break;
      case CarType.success:
        backgroundColor = MaterialStateProperty.all(Colors.green);
        overlayColor = MaterialStateProperty.resolveWith(
          (Set<MaterialState> states) {
            if (states.any(interactiveStates.contains)) {
              return Colors.green[300];
            } else {
              return Colors.white;
            }
          },
        );
        fontColor = Colors.white;
        break;
      case CarType.special:
        fontColor = Colors.orange;
        break;
      case CarType.disable:
        backgroundColor = MaterialStateProperty.all(Colors.grey[400]);
        break;
      default:
    }

    return SizedBox(
        width: () {
          if (listIndex.value == 6) {
            if (type == CarType.delete || type == CarType.success) {
              return 90.w;
            } else {
              return 54.w;
            }
          } else {
            return (type == CarType.delete || type == CarType.success)
                ? 122.w
                : 54.w;
          }
        }(),
        height: 80.w,
        child: type == CarType.hide
            ? Container()
            : ElevatedButton(
                onPressed: type == CarType.disable
                    ? null
                    : () {
                        ///震动
                        Vibrate.feedback(FeedbackType.light);
                        switch (type) {
                          case CarType.delete:
                            carNumberList[listIndex.value].value = '';
                            if (listIndex.value > 0) {
                              listIndex.value--;
                            }
                            break;
                          case CarType.success:
                            entryMain.remove();
                            isOpenKeyboard.value = false;
                            break;
                          default:
                            final RegExp isHanzi =
                                RegExp(r'^[\u4e00-\u9fa5]{0,}$');
                            if (listIndex.value == 7 &&
                                isHanzi.hasMatch(carNumberList[6].value)) {
                              carNumberList[6].value = '';
                            }
                            carNumberList[listIndex.value].value = title;
                            print(carNumberList[listIndex.value].value);
                            if (listIndex.value < 6) {
                              listIndex.value++;
                            }
                        }
                        getCarNumber();
                      },
                child: Text(title,
                    textAlign: TextAlign.center,
                    style: TextStyle(color: fontColor, fontSize: 30.sp)),
                style: ButtonStyle(
                    padding: MaterialStateProperty.all(EdgeInsets.zero),
                    enableFeedback: true,
                    overlayColor: overlayColor,
                    backgroundColor: backgroundColor),
              ));
  }

  ///输出车牌结果
  String getCarNumber() {
    initialValue.value = carNumberList.join();
    return carNumberList.join();
  }
}

///车牌按钮模型
class CarNumberInputButtonItem {
  CarNumberInputButtonItem({required this.title, this.type = CarType.normal});

  ///车牌名称
  String title;

  ///车牌类型
  CarType type;
}

///车牌类型
enum CarType {
  ///普通类型
  normal,

  ///主要
  primary,

  ///特殊
  special,

  ///删除
  delete,

  ///完成
  success,

  ///隐藏
  hide,

  ///禁用
  disable
}
